package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.Constant;
import com.example.demo.dao.CategoryRepository;
import com.example.demo.model.entity.CategoryModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping(value = Constant.API_VERSION + "/category")
public class CategoryController {

    @Autowired
    private CategoryRepository categoryRepository;

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseBody
    private CategoryModel create(@RequestBody CategoryModel model) {
        if (StringUtils.isEmpty(model.getCategoryName())) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "请填写分类名称"));
        }
        model.setCategoryId(UUID.randomUUID().toString());
        model.setCreateTime(System.currentTimeMillis());
        return categoryRepository.save(model);
    }

    @RequestMapping(value = "/{category_id}", method = RequestMethod.PUT)
    @ResponseBody
    private CategoryModel update(@PathVariable(value = "category_id") String categoryId, @RequestBody CategoryModel model) {
        CategoryModel categoryModel = categoryRepository.findOne(categoryId);
        if (categoryModel == null) {
            throw new RuntimeException(MessageFormat.format(Constant.ERROR_FORMAT, 400, "分类不存在"));
        }

        if (StringUtils.isNotEmpty(model.getCategoryName())) {
            categoryModel.setCategoryName(model.getCategoryName());
        }
        return categoryRepository.save(categoryModel);
    }

    @RequestMapping(value = "/{category_id}", method = RequestMethod.DELETE)
    @ResponseBody
    private void delete(@PathVariable(value = "category_id") String categoryId) {
        categoryRepository.delete(categoryId);
    }


    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    private JSONObject getByList(@RequestParam(value = "page_size", defaultValue = "10") String pageSize, @RequestParam(value = "page_number", defaultValue = "1") String pageNumber,
                                 @RequestParam(value = "keyword", defaultValue = "") final String keyword) {
        Page<CategoryModel> list = categoryRepository.findAll(new Specification<CategoryModel>() {
            @Override
            public Predicate toPredicate(Root<CategoryModel> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                if (StringUtils.isNotEmpty(keyword)) {
                    Path<String> namePath = root.get("categoryName");
                    predicateList.add(criteriaBuilder.like(namePath, "%" + keyword + "%"));
                }
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        }, new PageRequest(Integer.valueOf(pageNumber) - 1, Integer.valueOf(pageSize)));
        JSONObject result = new JSONObject();
        result.put("total", list.getTotalElements());
        result.put("items", list.getContent());
        return result;
    }

}
